package com.diyunapp.xilinapp.fragments;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.bean.CollectGoodsBean;
import com.diyunapp.xilinapp.details.GoodsDetailActivity;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.me.MyCollectActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class CollectGoodsFragment extends Fragment {


    @Bind(R.id.collectgoods_list)
    ListView collectgoodsList;
    @Bind(R.id.collectgoods_refresh_view)
    SwipeRefreshLayout collectgoodsRefreshView;
    @Bind(R.id.hona)
    TextView hona;
    private LayoutInflater inflater;
    private CollectGoodsAdapter collectGoodsAdapter;
    private List<CollectGoodsBean.DatasBean.FavoritesListBean> info = new ArrayList<CollectGoodsBean.DatasBean.FavoritesListBean>();
    //    private List collectgoods;
//    private static boolean state = false;
    private Handler handler;
    public int a;
    private SharedPreferences sp1;
    public int state;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        MyCollectActivity activity = (MyCollectActivity) getActivity();
        /**
         * 得到Activity的Handler
         */
        handler = activity.handler;
        /**
         * 加监听
         */
        activity.setButtonClickedListener1(new MyCollectActivity.OnButtonClickedListener1() {

            @Override
            public void onclicked(String s) {
                hona.setText(s);
                collectGoodsAdapter.notifyDataSetChanged();
//                a = s;
            }

        });
//        sp1 = getActivity().getSharedPreferences("DeleteCollect",1);
//        state = sp1.getInt("state",0);
//        Log.i("xiaogaladestate","state+"+state);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        // Inflate the layout for this fragment
        this.inflater = inflater;
        View view = inflater.inflate(R.layout.fragment_collect_goods, null);
        ButterKnife.bind(this, view);
        return view;

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

//        ButterKnife.bind(this, view);
        collectGoodsAdapter = new CollectGoodsAdapter(getContext());
        getInvesting();
        collectgoodsList.setAdapter(collectGoodsAdapter);

//        toast(String.valueOf(bundle));
        collectgoodsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String store_id = info.get(position).getGoods_id();
                Log.i("xiaogalade", "goods_id" + store_id);
                Intent intent = new Intent();
                intent.setClass(getActivity(), GoodsDetailActivity.class);
                intent.putExtra("GoodId", store_id);

                startActivity(intent);
            }
        });
        collectgoodsRefreshView.setColorSchemeColors(R.color.domain_orange, R.color.green,
                R.color.blue, R.color.yellow);

        collectgoodsRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d("zhangxiaoxidebug", "myordersSwiperefreshlayout onRefresh...");
                getInvesting();
            }
        });
        initView();
    }

    private void initView() {
//        SharedPreferences sp = getActivity().getSharedPreferences("DeleteCollect", 1);
//        state = sp.getBoolean("ifDeletestate", false);
        if (String.valueOf(state) == "false") {
            collectGoodsAdapter.notifyDataSetChanged();
        } else if (String.valueOf(state) == "true") {
            collectGoodsAdapter.notifyDataSetChanged();
        }
    }


    private void getInvesting() {
//        String url="http://www.xilingou.com/mobile/index.php?act=member_favorites&op=favorites_list&key=968c93be08e8f325162a2765748f6bb3";
        String url = "" + MainActivity.url + "act=member_favorites&op=favorites_list&key=" + MainActivity.myLogin.getLoginkey() + "";
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.GET, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        collectgoodsRefreshView.setRefreshing(false);
//                        bidFreshLv.onRefreshComplete();
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.getInt("code");
//                            Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show();

                            if (result == 200) {
                                info.clear();
                                JSONObject resultObject1 = resultObject.optJSONObject("datas");
                                JSONArray listArray = resultObject1.optJSONArray("favorites_list");
                                for (int i = 0; i < listArray.length(); i++) {


                                    JSONObject recordObject = listArray.getJSONObject(i);
                                    String goods_id = recordObject.optString("goods_id");
                                    String goods_name = recordObject.optString("goods_name");
//                                    Toast.makeText(getActivity(), store_name, Toast.LENGTH_SHORT).show();
                                    String goods_price = recordObject.optString("goods_price");
                                    String goods_marketprice = recordObject.optString("goods_marketprice");
                                    String goods_salenum = recordObject.optString("goods_salenum");
                                    String fav_id = recordObject.optString("fav_id");
                                    String goods_image_url = recordObject.optString("goods_image_url");
                                    info.add(new CollectGoodsBean.DatasBean.FavoritesListBean(goods_id, goods_name, goods_price, goods_marketprice
                                            , goods_salenum, fav_id, goods_image_url
                                    ));
                                    Log.i("============", "info1++++" + String.valueOf(info));
                                }
                                collectGoodsAdapter.setList(info);

                            } else {
                                collectgoodsRefreshView.setVisibility(View.GONE);
                                Toast.makeText(getActivity(), "您还没有收藏！", Toast.LENGTH_SHORT).show();

                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            collectgoodsRefreshView.setVisibility(View.GONE);
                            Toast.makeText(getActivity(), "查询失败，请联系客服处理！", Toast.LENGTH_SHORT).show();

                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        collectgoodsRefreshView.setRefreshing(false);
                        collectgoodsRefreshView.setVisibility(View.GONE);
                        Toast.makeText(getActivity(), "查询失败，请检查您的网络！", Toast.LENGTH_SHORT).show();

                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    public class CollectGoodsAdapter extends BaseAdapter {
        private LayoutInflater inflater;

        private List<CollectGoodsBean.DatasBean.FavoritesListBean> info =
                new ArrayList<CollectGoodsBean.DatasBean.FavoritesListBean>();
        private Context context;

        //        private LendNoDebtFragment lendNoDebtFragment;
        public CollectGoodsAdapter(Context context) {
            super();
            this.context = context;
        }

        public void setList(List<CollectGoodsBean.DatasBean.FavoritesListBean> list) {
            this.info = list;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return null == info ? 0 : info.size();
        }

        @Override
        public Object getItem(int position) {
            return null == info ? null : info.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        private ViewHolder viewHolder;

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (null == convertView) {
                LayoutInflater layoutInflater = LayoutInflater.from(context);
                convertView = layoutInflater.inflate(R.layout.item_fragment_collectgoods, null);

                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            CollectGoodsBean.DatasBean.FavoritesListBean bean = info.get(position);


            viewHolder.rel_total.setTag(position);
            viewHolder.buycarDeleteallTv.setTag(position);
            viewHolder.introduceGoods.setText(bean.getGoods_name());
            viewHolder.introducePrice.setText(bean.getGoods_price());
            viewHolder.oldPrice.setText(bean.getGoods_marketprice());
            viewHolder.saleNum.setText(bean.getGoods_salenum());
            String datas = bean.getGoods_image_url();
            Picasso.with(context)
                    .load(datas)
                    .resize(200, 200)
                    .centerCrop()
                    .placeholder(R.drawable.list_default)
                    .error(R.drawable.list_default)
                    .into(viewHolder.goodsImage);
            final String id = bean.getFav_id();
            String s= hona.getText().toString().trim();
            if (s == "1"||s.equals("1")) {
                viewHolder.buycarDeleteallTv.setVisibility(View.VISIBLE);
            } else if (s == "2"||s.equals("2")) {
                viewHolder.buycarDeleteallTv.setVisibility(View.GONE);
            }
            viewHolder.buycarDeleteallTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    Log.i("111111","11111111111");
                    initDelete(id);
                    info.clear();
                    getInvesting();
                }
            });
            return convertView;
        }


        class ViewHolder {
            @Bind(R.id.goods_image)
            ImageView goodsImage;
            @Bind(R.id.introduce_goods)
            TextView introduceGoods;
            @Bind(R.id.introduce_price)
            TextView introducePrice;
            @Bind(R.id.old_price)
            TextView oldPrice;
            @Bind(R.id.sale_num)
            TextView saleNum;
            @Bind(R.id.buycar_deleteall_tv)
            TextView buycarDeleteallTv;
            @Bind(R.id.rel_total)
            RelativeLayout rel_total;

            ViewHolder(View view) {
                ButterKnife.bind(this, view);
                oldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            }
        }

    }

    public void initDelete(String id) {
        String url = "http://www.xilingou.com/mobile/index.php?" +
                "act=goods&op=del_scstore&member_id=" + MainActivity.myLogin.getMemberid() + "&fav_id=" + id + "&fav_type=goods";
        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int code = resultObject.optInt("code");
                            if (code == 200) {
                                String date = resultObject.optString("date");
                                toast(date);
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            toast("查询失败");
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {

                        toast("请求失败");
                    }
                });

    }

    public void toast(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }
}
